//
//  QLMAddInvoicesVC.m
//  Xiaomakuaixiu
//
//  Created by 邬俊涛 on 2018/3/10.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "QLMAddInvoicesVC.h"
#import "QLMInvoiceTopCell.h"
#import "QLMInvoiceMidCell.h"
#import "QLMInvoiceBottomCell.h"
#import "QShowSubAlertView.h"
#import "MBProgressHUD+NJ.h"
@interface QLMAddInvoicesVC ()<UITableViewDataSource,UITableViewDelegate>{
    QLMInvoiceMidCell *midCell;
    QLMInvoiceBottomCell *bottomCell;
    CustomTextField *ctTextField;
    BOOL _searchRusultIsYes;
    id _tempData;
    UITableView *_addinvoicetableview;
    NSDictionary *_dicInfo;
    UIControl *_maskView;
    QShowSubAlertView *_subView;
    
    CGFloat W;
    CGFloat H;
}

@end

@implementation QLMAddInvoicesVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UIView *topBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 40)];
    topBackView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:topBackView];
    
    NSString *telStr=@"* 请确保您填写信息的准确性，包含英文输入法下的括号，您每天有10次校验机会";
    NSMutableAttributedString *aString=[[NSMutableAttributedString alloc] initWithString:telStr];
    [aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
    
    UILabel *addreTipLabel=[[UILabel alloc] initWithFrame:CGRectMake(20, 0, kScreen_width-40, 40)];
    addreTipLabel.font=[UIFont systemFontOfSize:13];
    addreTipLabel.numberOfLines=0;
    addreTipLabel.textColor=[UIColor blackColor];
    addreTipLabel.attributedText=aString;
    addreTipLabel.textAlignment=NSTextAlignmentLeft;
    [topBackView addSubview:addreTipLabel];
    
    
    CGRect tabFrame = CGRectMake(0, 40, kScreen_width, kScreen_height-QLM_StatusBarAndNavigationBarHeight-IOS11_OR_LATER_SPACE(34)-40);
    
    _addinvoicetableview=[[UITableView alloc] initWithFrame:tabFrame style:UITableViewStylePlain];
    _addinvoicetableview.backgroundColor=[UIColor clearColor];
    _addinvoicetableview.delegate=self;
    _addinvoicetableview.dataSource=self;
    _addinvoicetableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    _addinvoicetableview.showsVerticalScrollIndicator=NO;
    _addinvoicetableview.showsHorizontalScrollIndicator=NO;
    _addinvoicetableview.tableFooterView=[UIView new];
    _addinvoicetableview.tableHeaderView=[UIView new];
    [self.view addSubview:_addinvoicetableview];
    
    if (@available(iOS 11.0, *)) {
        _addinvoicetableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addInvoicesAlert{
    
    if ([_custType isEqualToString:@"2"]) {
        if (![ClientTool isNull:ctTextField.text]||ctTextField.text.length==0) {
            ETToast(@"请输入公司名称");
            return;
        }
        if (![ClientTool isNull:midCell.companyNameTF.text]||midCell.companyNameTF.text.length==0) {
            ETToast(@"请输入公司税号");
            return;
        }
    }else{
        
        if (![ClientTool isNull:bottomCell.companyNameTF.text]||bottomCell.companyNameTF.text.length==0) {
            ETToast(@"请输入公司名称");
            return;
        }
//        if (![ClientTool isNull:bottomCell.shuihaoTF.text]||bottomCell.shuihaoTF.text.length==0) {
//            ETToast(@"请输入公司税号");
//            return;
//        }
//        if (![ClientTool isNull:bottomCell.bankAddressTF.text]||bottomCell.bankAddressTF.text.length==0) {
//            ETToast(@"请输入公司地址");
//            return;
//        }
//        if (![ClientTool isNull:bottomCell.bankPhoneTF.text]||bottomCell.bankPhoneTF.text.length==0) {
//            ETToast(@"请输入公司电话");
//            return;
//        }
//        if (![ClientTool isNull:bottomCell.bankNameTF.text]||bottomCell.bankNameTF.text.length==0) {
//            ETToast(@"请输入开户银行");
//            return;
//        }
//        if (![ClientTool isNull:bottomCell.bankAccountTF.text]||bottomCell.bankAccountTF.text.length==0) {
//            ETToast(@"请输入银行账号");
//            return;
//        }

    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定提交发票信息？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                         }];
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self addInvoicesData];
                                                          }];
    [alert addAction:cancelAction];
    [alert addAction:defaultAction];

    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)addInvoicesData{
    NSString *userID=[[NSUserDefaults standardUserDefaults] objectForKey:kJrUserId];
    NSMutableDictionary *paraDic=[NSMutableDictionary dictionary];
    
    [paraDic setObject:userID forKey:@"jrUserId"];
    [paraDic setObject:_custType forKey:@"custType"];//2普票  3专票
    
    if ([_custType isEqualToString:@"2"]) {
        [paraDic setObject:ctTextField.text forKey:@"companyName"];
        [paraDic setObject:midCell.companyNameTF.text forKey:@"taxNo"];
    }else {
        [paraDic setObject:bottomCell.companyNameTF.text forKey:@"companyName"];
        [paraDic setObject:bottomCell.shuihaoTF.text forKey:@"taxNo"];
        [paraDic setObject:bottomCell.bankNameTF.text forKey:@"bankName"];
        [paraDic setObject:bottomCell.bankAccountTF.text forKey:@"bankAccount"];
        [paraDic setObject:bottomCell.bankPhoneTF.text forKey:@"companyTel"];
        [paraDic setObject:bottomCell.bankAddressTF.text forKey:@"companyAdd"];
    }
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPathAndFormData:@"/rest/appUser/saveInvoices" withParamers:paraDic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            [self.navigationController popViewControllerAnimated:YES];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *backView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 5)];
    backView.backgroundColor=[UIColor clearColor];
    return backView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_custType isEqualToString:@"2"]){
        return 248;
    }
    return 444;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([_custType isEqualToString:@"2"]){
        midCell=[QLMInvoiceMidCell cellWithTableView:tableView];
        midCell.selectionStyle=UITableViewCellSelectionStyleNone;
        [midCell.commitBtn addTarget:self action:@selector(addInvoicesAlert) forControlEvents:UIControlEventTouchUpInside];
        
        midCell.shuihaoTextField.hidden=YES;
        
        ctTextField = [[CustomTextField alloc]initWithFrame:CGRectMake(100, 50, kScreen_width-100-20, 30) placeholder:@"请输入公司名称" clear:YES leftView:nil fontSize:14];
        [midCell addSubview:ctTextField];
        
        return midCell;
    }
    bottomCell=[QLMInvoiceBottomCell cellWithTableView:tableView];
    bottomCell.selectionStyle=UITableViewCellSelectionStyleNone;
    [bottomCell.searchBtn addTarget:self action:@selector(searchCompanyInfo) forControlEvents:UIControlEventTouchUpInside];
    [bottomCell.commitBtn addTarget:self action:@selector(addInvoicesAlert) forControlEvents:UIControlEventTouchUpInside];
    
    if(_searchRusultIsYes){
        bottomCell.shuihaoTipLabel.hidden = NO;
        bottomCell.shuihaoTF.hidden = NO;
//        bottomCell.shuihaoTF.enabled = NO;
        bottomCell.addrTipLabel.hidden = NO;
        bottomCell.bankNameTF.hidden = NO;
//         bottomCell.bankNameTF.enabled = NO;
        bottomCell.companyTipLabel.hidden = NO;
        bottomCell.bankAccountTF.hidden = NO;
//        bottomCell.bankAccountTF.enabled = NO;
        bottomCell.bankNameTipLabel.hidden = NO;
        bottomCell.bankPhoneTF.hidden = NO;
//        bottomCell.bankPhoneTF.enabled = NO;
        bottomCell.bankAccountTipLabel.hidden = NO;
        bottomCell.bankAddressTF.hidden = NO;
//        bottomCell.bankAddressTF.enabled = NO;
        bottomCell.img2.hidden = NO;
        bottomCell.img3.hidden = NO;
        bottomCell.img4.hidden = NO;
        bottomCell.img5.hidden = NO;
        bottomCell.img6.hidden = NO;
        bottomCell.companyNameTF.text = [_dicInfo objectForKey:@"Name"];
        bottomCell.shuihaoTF.text = [_dicInfo objectForKey:@"CreditCode"];
        bottomCell.bankAddressTF.text = [_dicInfo objectForKey:@"Address"];
        bottomCell.bankPhoneTF.text = [_dicInfo objectForKey:@"Tel"];
        bottomCell.bankNameTF.text = [_dicInfo objectForKey:@"Bank"];
        bottomCell.bankAccountTF.text = [_dicInfo objectForKey:@"BankAccount"];
        bottomCell.searchBtn.hidden = YES;
        bottomCell.commitBtn.hidden = NO;
        
    }else{
        bottomCell.shuihaoTipLabel.hidden = YES;
        bottomCell.shuihaoTF.hidden = YES;
        bottomCell.addrTipLabel.hidden = YES;
        bottomCell.bankNameTF.hidden = YES;
        bottomCell.companyTipLabel.hidden = YES;
        bottomCell.bankAccountTF.hidden = YES;
        bottomCell.bankNameTipLabel.hidden = YES;
        bottomCell.bankPhoneTF.hidden = YES;
        bottomCell.bankAccountTipLabel.hidden = YES;
        bottomCell.bankAddressTF.hidden = YES;
        bottomCell.img2.hidden = YES;
        bottomCell.img3.hidden = YES;
        bottomCell.img4.hidden = YES;
        bottomCell.img5.hidden = YES;
        bottomCell.img6.hidden = YES;
        bottomCell.searchBtn.hidden = NO;
        bottomCell.commitBtn.hidden = YES;
    }
    
    
    return bottomCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


#pragma mark 专票、普票查询
-(void)searchCompanyInfo{
    NSString *name = @"";
    if ([_custType isEqualToString:@"2"]) {
        if (![ClientTool isNull:ctTextField.text]||ctTextField.text.length==0) {
            ETToast(@"请输入公司名称");
            return;
        }
        if (![ClientTool isNull:midCell.companyNameTF.text]||midCell.companyNameTF.text.length==0) {
            ETToast(@"请输入公司税号");
            return;
        }
        name = midCell.companyNameTF.text;
    }
    else{
        
        if (![ClientTool isNull:bottomCell.companyNameTF.text]||bottomCell.companyNameTF.text.length==0) {
            ETToast(@"请输入公司名称");
            return;
        }
        name = bottomCell.companyNameTF.text;
    }
    // 1 创建URL对象
    NSString *companyName = [NSString stringWithFormat:@"http://i.yjapi.com/ECICreditCode/GetCreditCodeNew?key=72cbdd0dcf7f40c588335ac94e8c7fc7&dtype=json&keyWord=%@",name];
    companyName=[companyName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    NSURL *url = [NSURL URLWithString:companyName];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:10];
    //连接服务器
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
   
    [connection start];
  
    [MBProgressHUD showMessage:@"信息核对中,请耐心的等待" toView:nil WithMode:MBProgressHUDModeIndeterminate ];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
        _tempData = [NSMutableData data];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
        [_tempData appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
   
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"dic:%@",dict);
  
    [MBProgressHUD hideHUDForView:nil];
    if (([[dict objectForKey:@"Status"]intValue] == 200)) {
        
         [MBProgressHUD show:[dict objectForKey:@"Message"] icon:@"zq_ts" view:nil];
        
    }
    
    if(!([[dict objectForKey:@"Status"]intValue] == 200)){

          [MBProgressHUD show:[dict objectForKey:@"Message"] icon:@"cw_ts" view:nil];
//         ETToast([dict objectForKey:@"Message"]);
        
        
        
    }else{
    
        _dicInfo = [dict objectForKey:@"Result"];
        
        _searchRusultIsYes = YES;
    

        [_addinvoicetableview reloadData];
        

    }
    
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
    [MBProgressHUD hideHUDForView:nil];
    NSString *errorString = [NSString stringWithFormat:@"%@",error];
     [MBProgressHUD show:errorString icon:@"cw_ts" view:nil];
}
@end
